/*******************************************************************************
 *    系统名称   ：GMAgent服务系统
 *    公司      ： 成都欢娱乐互动
 *    文件名    ： NetServer.java
 *              (C) Copyright joyct Corporation 2011
 *               All Rights Reserved.
 * *****************************************************************************
 *    注意： 本内容仅限于 成都欢娱乐互动公司内部使用，禁止转发
 ******************************************************************************/
package com.ricky.core.net;

import java.net.InetSocketAddress;

import org.apache.log4j.Logger;
import org.apache.mina.core.service.IoConnector;
import org.apache.mina.core.service.IoHandler;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

import com.ricky.core.net.abs.Request;
import com.ricky.core.net.abs.NetServer;
import com.ricky.core.net.msg.Context;
import com.ricky.core.net.protocol.AMF3ProtocolCodecFactory;
import com.ricky.core.net.utils.Attributes;

/***
 * NetServer.java</br>
 * 
 * @author pu
 * @Data 2011-11-2</br>
 * @version v0.1</br>
 * @Discription
 ***/
public class ClientServer extends NetServer implements IoHandler {

	protected static Logger log = Logger.getLogger(ClientServer.class);

	private IoConnector connector;
	private String host;
	
	/**
	 * @param port
	 * @param maxConnection
	 */
	public ClientServer(String host, int port) {

		super(port, 10);
		this.host = host;

	}

	/**
	 * 开启服务
	 */
	@Override
	public void start() {
		connector.connect(new InetSocketAddress(host, port));
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.ricky.core.net.abs.NetServer#init()
	 */
	@Override
	public void init() {

		connector = new NioSocketConnector();
		connector.getSessionConfig().setMaxReadBufferSize(1024);
		connector.getFilterChain().addLast("Logging", new LoggingFilter());
		connector.getFilterChain().addLast("codec",
				new ProtocolCodecFilter(new AMF3ProtocolCodecFactory()));
		
		connector.setHandler(this);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.apache.mina.core.service.IoHandler#exceptionCaught(org.apache.mina
	 * .core.session.IoSession, java.lang.Throwable)
	 */
	@Override
	public void exceptionCaught(IoSession arg0, Throwable arg1)
			throws Exception {
		log.error(arg1.getMessage(),arg1);
	}

	/**
	 * 消息来了
	 * 
	 * @see org.apache.mina.core.service.IoHandler#messageReceived(org.apache.mina.core.session.IoSession,
	 *      java.lang.Object)
	 */
	@SuppressWarnings("unchecked")
	@Override
	public void messageReceived(IoSession session, Object data)
			throws Exception {
		Context<?> context = (Context<?>) data;
		
		Request req = (Request) session
				.getAttribute(Attributes.CONN);
		if (req == null) {
			req = new MinaRequest(session);
			session.setAttribute(Attributes.CONN, req);
		}
		
		if (!session.isClosing() && session.isConnected())
			iMessageListener.onMessageArrived(req,context);		
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.apache.mina.core.service.IoHandler#messageSent(org.apache.mina.core
	 * .session.IoSession, java.lang.Object)
	 */
	@Override
	public void messageSent(IoSession arg0, Object arg1) throws Exception {
//		log.info(arg0.getRemoteAddress()+"消息以发送:"+arg1);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.apache.mina.core.service.IoHandler#sessionClosed(org.apache.mina.
	 * core.session.IoSession)
	 */
	@Override
	public void sessionClosed(IoSession session) throws Exception {

		if (iServerListener != null) {
			Request conn = (Request) session
					.getAttribute(Attributes.CONN);

			if (conn != null ) {
				iServerListener.onConnectionClosed(conn);
			}
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.apache.mina.core.service.IoHandler#sessionCreated(org.apache.mina
	 * .core.session.IoSession)
	 */
	@Override
	public void sessionCreated(IoSession session) throws Exception {
		session.setAttribute(Attributes.RECEIVE_MSG_COUNT, 0);
		if (iServerListener != null) {
			Request conn = new MinaRequest(session);
			session.setAttribute(Attributes.CONN, conn);
			iServerListener.onConnectionCreated(conn);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.apache.mina.core.service.IoHandler#sessionIdle(org.apache.mina.core
	 * .session.IoSession, org.apache.mina.core.session.IdleStatus)
	 */
	@Override
	public void sessionIdle(IoSession arg0, IdleStatus arg1) throws Exception {

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.apache.mina.core.service.IoHandler#sessionOpened(org.apache.mina.
	 * core.session.IoSession)
	 */
	@Override
	public void sessionOpened(IoSession session) throws Exception {

//		log.info(session+"连接已打开");
		// 连接打开
		if (iServerListener != null) {
			Request conn = (Request) session
					.getAttribute(Attributes.CONN);
			if (conn != null ) {
				iServerListener.onConnectionOpend(conn);
			}
		}
	}

}
